package com.oasys.interceptor;

import com.oasys.annotations.RequiredToken;
import com.oasys.service.SysUserService;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



/**
 * @author mis_wu
 * @date 2022/05/12
 * 自定义拦截器 拦截请求 验证登录信息
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private SysUserService sysUserService;

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request
            , @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {

            boolean requiredToken = ((HandlerMethod)handler).getMethod().isAnnotationPresent(RequiredToken.class);
            if (requiredToken) {
                return true;
            }

            String uri = request.getRequestURI();
            if (uri.startsWith("/saveFiles")) {
                return true;
            }

            try {
                String token = request.getHeader("Authorization");
                sysUserService.setLoginUser(token);
                return true;
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }

            response.setStatus(401);
            return false;
        }
        return false;
    }

}
